package com.ufrn_access;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Arrays;

import com.service.SigaaCalls;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.TextView;

public class DisciplinasActivity extends Activity {
	public static final String PREFS_NAME = "MyPrefsFile";
	static SharedPreferences settings;
	SharedPreferences.Editor editor;
	
	private ListView disciplinaslistView;
	private ArrayAdapter<String> listAdapter;
	SigaaCalls sig;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_disciplinas);

		disciplinaslistView = (ListView) findViewById(R.id.listViewDisciplinas);
		disciplinaslistView.removeAllViewsInLayout();
		sig = SigaaCalls.getInstance();
		//-------------------------------------------------------------------
		settings = getSharedPreferences(PREFS_NAME,0);
		editor = settings.edit();

		String username = settings.getString("username", "-");
		String password = settings.getString("password", "-");
		//-------------------------------------------------------------------
		String[] disciplinas = null;
		try {
			disciplinas = sig.getDadosAluno(username, password);
		} catch (ConnectException e) {
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			  dialog.setTitle("Erro");
			  
			  dialog.setMessage("Não foi possivel alcançar o servidor, tente novamente mais tarde\n");
			 
			  dialog.show();
			  
		}
		
		if (disciplinas != null){
		
			ArrayList<String> disciplinesList = new ArrayList<String>();
			disciplinesList.addAll(Arrays.asList(disciplinas));
			listAdapter = new ArrayAdapter<String>(this, R.layout.listviewlinha,
					disciplinesList);
			
			disciplinaslistView.setAdapter(listAdapter);
	
			disciplinaslistView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
				
				public void onItemClick(AdapterView<?> arg0, View v, int arg2,
						long arg3) {
					TextView t = (TextView) v;
					System.out.println("alguem clicou algo"+t.getText());
					
					Intent intent = new Intent(DisciplinasActivity.this, DetalhesDisciplinaActivity.class);
			    	intent.putExtra("nome_disciplina", t.getText());
					startActivity(intent);
					
				}
	
			
	
			});
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
